// main.js

// Modules to control application life and create native browser window
const { app, BrowserWindow, Menu, ipcMain } = require('electron')
const path = require('path')
let {openServer} = require("./server.js");   //开启本地http服务

// 加入以下两项使跨域问题消失（配合BrowserWindow的webSecurity选项，以及下文的onHeadersReceived回调）
app.commandLine.appendSwitch('disable-web-security');
app.commandLine.appendSwitch("disable-site-isolation-trials");
app.commandLine.appendSwitch('allow-file-access-from-files');
app.commandLine.appendSwitch('disable-features=SameSiteByDefaultCookies');


// process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = true // 这个没什么用

//开启服务
openServer().then(res=>{
  console.log("返回:"+res);
}).catch((e)=>{
  dialog.showErrorBox("提示信息",e);
});



var mainWindow = null

// 菜单配置
// require('./menu')


const createWindow = () => {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1300,
    height: 800,
    autoHideMenuBar: true, // 隐藏菜单
    webPreferences: {
      webSecurity: false,
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // 拦截并接管新窗口的打开
  mainWindow.webContents.setWindowOpenHandler( details => {
    console.log('WindowOpenHandler details:', JSON.stringify(details))
    // 在这里拦截到url并调用index.html里面的方法去通过iframe1打开
    mainWindow.webContents.send('open-url', details.url) // 把url通过事件发送进去，该事件在preload中通过ipcRenderer.on('open-url')关联
		return { action: 'deny' } // 拒绝创建新窗口
  })

  mainWindow.webContents.session.webRequest.onBeforeSendHeaders(
    (details, callback) => {
      // if(details.requestHeaders['Sec-Fetch-Dest']){
      //   delete details.requestHeaders['Sec-Fetch-Dest']

      // }
      callback({ requestHeaders: { 
        // Origin: '*', // 公需科目加了这个会返回403
        // Referer: 'https://ptce.gx12333.net/',
        Referer: details.url,
        ...details.requestHeaders,
        // 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        // 'sec-ch-ua': '"Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"',
        // 'sec-ch-ua-mobile': '?0',
        // 'sec-ch-ua-platform': '"Windows"',
        // 'Sec-Fetch-Site': 'same-origin',
        // 'Sec-Fetch-Dest': 'document',
        // 'Sec-Fetch-Site': 'none',
        // UA彻底改掉
        'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36",
      } });
    },
  );

  // 这个工作下文做了
  // mainWindow.webContents.session.webRequest.onHeadersReceived((details, callback) => {
  //   callback({
  //     responseHeaders: {
  //       'Access-Control-Allow-Origin': ['*'],
  //       ...details.responseHeaders,
  //     },
  //   });
  // });

 
  // 允许iframe访问第三方url、修改cookies同源策略（否则全都无法存储cookies）、清除Content-Security-Policy
  mainWindow.webContents.session.webRequest.onHeadersReceived({ urls: [ "*://*/*" ] },
    (details, callback)=>{
      if(details.responseHeaders['X-Frame-Options']){
        delete details.responseHeaders['X-Frame-Options'];
      } else if(details.responseHeaders['x-frame-options']) {
        delete details.responseHeaders['x-frame-options'];
      }
      if(details.responseHeaders && details.responseHeaders['Set-Cookie']){
        for(let i = 0;i < details.responseHeaders['Set-Cookie'].length;i++)
          details.responseHeaders['Set-Cookie'][i] += ";SameSite=None;Secure";
      }

      if(details.responseHeaders['Content-Security-Policy']){
        delete details.responseHeaders['Content-Security-Policy'];
      }

      details.responseHeaders['Access-Control-Allow-Origin'] = ['*']

      callback({
        responseHeaders: details.responseHeaders,
        cancel: false, 
      });
    }
  );


  // and load the index.html of the app.
  mainWindow.loadFile('./src/index.html') //https://ptce.gx12333.net/  //index.html
  // mainWindow.loadURL('https://ptce.gx12333.net/') //https://ptce.gx12333.net/  //index.html

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()

  mainWindow.maximize()



}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow()


  app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
      
    // ///////////////////////////////////
    console.log('mainWindow.webContents.mainFrame.frames', mainWindow.webContents.mainFrame.frames)
    // ////////////////////////////////////

    // 

  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  
  if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

